import { interval, Observable } from 'rxjs';
import { Component, Input, OnInit } from '@angular/core';
import { map, takeWhile } from 'rxjs/operators';

@Component({
  selector: 'app-count-down-rx',
  templateUrl: './count-down-rx.component.html',
  styleUrls: ['./count-down-rx.component.less'],
})
export class CountDownRxComponent implements OnInit {
  @Input() startTime: Date = new Date();
  @Input() endTime!: Date;
  countDown$!: Observable<string>;
  constructor() {}

  ngOnInit() {
    this.countDown$ = this.startCountDown(this.startTime, this.endTime);
  }
  diffDateInSec = (start: Date, end: Date): number => {
    const diff = end.getTime() - start.getTime();
    return Math.floor(diff) / 1000;
  };
  startCountDown = (start: Date, end: Date) => {
    return interval(1000).pipe(
      map((elapse) => this.diffDateInSec(start, end) - elapse),
      // 这里表示当倒计时小于0的时候自动结束当前流
      takeWhile((gap) => gap >= 0),
      map((sec) => ({
        day: Math.floor(sec / 3600 / 24),
        hour: Math.floor((sec / 3600) % 24),
        minute: Math.floor((sec / 3600) % 60),
        second: Math.floor(sec % 60),
      })),
      map(
        ({ day, hour, minute, second }) =>
          `${day}天${hour}时${minute}分${second}秒`
      )
    );
  };
}
